var timeout_json = function(data, $window) {
	if(data.returnCode == 999994) {
		var ss = 3;
		layer.msg(data.returnMessage + "！<strong class='Ajax_Out'>" + ss + "</strong> 秒后前往登录页", 50, -1);
		var picInt = setInterval(function() {
			if(ss >= 1) {
				ss = ss - 1;
				$('.Ajax_Out').text(ss);
			} else {
				clearInterval(picInt);
				try {
					$window.parent.location.href = data.returnData;
					$window.location.href = data.returnData;
				} catch(e) {
					log('timeout!')
				}
			}
		}, 1000);
		return false;
	}
}

var app = angular.module("nameEditApp", []),
	ifm_id = UI.getParameterByName('ifm_id'),
	groupIde = UI.getParameterByName('groupId'),
	opt_type;
app.config(function($httpProvider) {
	$httpProvider.defaults.headers.put['Content-Type'] = 'application/x-www-form-urlencoded';
	$httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
	$httpProvider.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
});

app.controller('editCtrl', function($scope, $http, $window, $timeout) {
	var vm = $scope.vm = {
		ifm_id: null,
		ifm_name: null,
		ifm_pushed: null,
		ifm_type: null,
		ifm_note: "",
		groupId:"",
		ifm_categoryName:null,
		ifm_getChannel: null,
		ifm_notChannel: null,
		ifm_getWechatId: null,
		ifm_notWechatId: null,
		ifm_getBloggerId: null,
		ifm_notBloggerId: null,
		ifm_getBbsName: null,
		ifm_notBbsName: null,
		ifm_getKeyword: null,
		ifm_notKeyword: null,
		ifm_isdelete: null,
		ifm_matePattern: null,
		ifm_filterPattern: null,
		ifm_isSensitivity:null
	};
	
	$scope.vshow = true;
	if(ifm_id && !$("#categoriesValue").val() && !$("#categoryNameId").val()){
		$scope.vshow = false; 
	}
	$("#categoryNameId").blur(function(){
		if(ifm_id && !$("#categoriesValue").val() && !$("#categoryNameId").val()){
			$scope.vshow = false; 
			$scope.$apply();
		}
	});
	
	var avoidDup = true;
	$scope.domAjax = function(e) {
		if(e==="release" || e==="next") {
			if(avoidDup==false){
				return false;
			}
			
			$scope.vm.ifm_pushed = $("#addIsSign").val();
			$scope.vm.ifm_isSensitivity = $("#addIsSensitive").val();
			if($scope.vm.ifm_pushed==1){
				if($("#push_app").hasClass("checked")||$("#push_msg").hasClass("checked")){
					if($("#push_app").hasClass("checked")){
						$scope.vm.ifm_type="app"; 
					}
					if($("#push_msg").hasClass("checked")){
						$scope.vm.ifm_type="note"; 
					}
					if($("#push_app").hasClass("checked")&&$("#push_msg").hasClass("checked")){
						$scope.vm.ifm_type="app|note";
					}
				}else{
					$scope.vm.ifm_pushed=2;
				}
			}else{
				$scope.vm.ifm_type = "None";
//				if($("#push_app").hasClass("checked")||$("#push_msg").hasClass("checked")){
//					layer.msg("请确认是否推送！", 2, -1);
//					$scope.vm.ifm_pushed=2;
//				}
			}
/*			if($scope.vm.ifm_note==null||$scope.vm.ifm_note==""){
				$scope.vm.ifm_note = null;
			}*/
			if($scope.vm.ifm_getChannel==null||$scope.vm.ifm_getChannel==""){
				$scope.vm.ifm_getChannel = "None";
			}
			if($scope.vm.ifm_notChannel==null||$scope.vm.ifm_notChannel==""){
				$scope.vm.ifm_notChannel = "None";
			}
			if($scope.vm.ifm_getWechatId==null||$scope.vm.ifm_getWechatId==""){
				$scope.vm.ifm_getWechatId = "None";
			}
			if($scope.vm.ifm_notWechatId==null||$scope.vm.ifm_notWechatId==""){
				$scope.vm.ifm_notWechatId = "None";
			}
			if($scope.vm.ifm_getBloggerId==null||$scope.vm.ifm_getBloggerId==""){
				$scope.vm.ifm_getBloggerId = "None";
			}
			if($scope.vm.ifm_notBloggerId==null||$scope.vm.ifm_notBloggerId==""){
				$scope.vm.ifm_notBloggerId = "None";
			}
			if($scope.vm.ifm_getBbsName==null||$scope.vm.ifm_getBbsName==""){
				$scope.vm.ifm_getBbsName = "None";
			}
			if($scope.vm.ifm_notBbsName==null||$scope.vm.ifm_notBbsName==""){
				$scope.vm.ifm_notBbsName = "None";
			}
			if($scope.vm.ifm_getKeyword==null||$scope.vm.ifm_getKeyword==""){
				$scope.vm.ifm_getKeyword = null;
			}
			if($scope.vm.ifm_notKeyword==null||$scope.vm.ifm_notKeyword==""){
				$scope.vm.ifm_notKeyword = null;
			}
			//将要传递的参数
			var params = {
				ifm_id: $scope.vm.ifm_id,
				ifm_name: $scope.vm.ifm_name,
				ifm_pushed: $scope.vm.ifm_pushed,
				ifm_type: $scope.vm.ifm_type,
				ifm_note: $scope.vm.ifm_note,
				groupId: $("#groupIds").val(),
				ifm_category: $("#categoriesValue").val()||"",
				ifm_categoryName: $("#categoryNameId").val()||"",
				oldCategory: $scope.oldCategory||"",
				oldCategoryName: $scope.oldCategoryName||"",
				
				ifm_getChannel: $scope.vm.ifm_getChannel,
				ifm_notChannel: $scope.vm.ifm_notChannel,
				ifm_getWechatId: $scope.vm.ifm_getWechatId,
				ifm_notWechatId: $scope.vm.ifm_notWechatId,
				ifm_getBloggerId: $scope.vm.ifm_getBloggerId,
				ifm_notBloggerId: $scope.vm.ifm_notBloggerId,
				ifm_getBbsName: $scope.vm.ifm_getBbsName,
				ifm_notBbsName: $scope.vm.ifm_notBbsName,
				ifm_getKeyword: $scope.vm.ifm_getKeyword,
				ifm_notKeyword: $scope.vm.ifm_notKeyword,
				ifm_isdelete: $scope.vm.ifm_isdelete,
				ifm_matePattern: $scope.vm.ifm_matePattern,
				ifm_filterPattern: $scope.vm.ifm_filterPattern,
				ifm_isSensitivity: $scope.vm.ifm_isSensitivity
			};
			
			if((ifm_id && $("#categoriesValue").val()==null && $("#categoryNameId").val()!=null)||(ifm_id && $("#categoriesValue").val()!=null && $("#categoryNameId").val()==null)){
				$scope.vshow = true;
				avoidDup = true;
				return false;
			}else if(ifm_id && $("#categoriesValue").val() && $scope.vm.ifm_categoryName==null){
				$scope.vshow = true;
				avoidDup = true;
				return false;
			}

			var urls = ['iformation/addIformation.do', 'iformation/modifyIformation.do'];
			if(params.ifm_name!=null && params.ifm_note!=null){
				if($("#groupIds").val()!="" && !ifm_id){
					if($scope.vm.ifm_categoryName==null){
						return false;
					}else if(params.ifm_category ==""){
						layer.msg("请选择所属类别！",2,-1);
						return false;
					}
				}

				if( $scope.vm.ifm_pushed==2){
					layer.msg("请选择推送的方式！", 2, -1);
					return false;
				}
				avoidDup =false;
				if(e==="next"){
					//利用post表单的方式进行参数传递
					function openPostWindow(postUrl, paramsObj, name) {  
			            var postForm = document.createElement("form");      
				            postForm.id = "postForm";      
				            postForm.method = "post";      
				            postForm.action = postUrl;      
				            postForm.target = name;      
			             
			            // 获取参数的公用方法 
			            function getParams(objName,objValue){
			                var objInput = document.createElement("input");      
				                objInput.type="hidden";      
				                objInput.name= objName;  
				                objInput.value= objValue;    
				                postForm.appendChild(objInput);   
			            }
			            
			            getParams("ifm_name",params.ifm_name); 
			            getParams("ifm_note",params.ifm_note); 
			            getParams("groupId",params.groupId);
			            getParams("ifm_category",params.ifm_category);
			            getParams("ifm_categoryName",params.ifm_categoryName); 
			            getParams("ifm_type",params.ifm_type); 
			            getParams("ifm_pushed",params.ifm_pushed); 
			                                 
			            document.body.appendChild(postForm);
			            postForm.submit();
			            document.body.removeChild(postForm);
					}
		            openPostWindow('programmeNewNext.jsp',params,name);
				}else{
					if((opt_type==1 && params.ifm_categoryName=="" && params.ifm_category!="" && params.groupId) ||(opt_type==1 && params.ifm_categoryName!="" && params.ifm_category=="" && params.groupId)){
						$scope.vshow = true;
						avoidDup = true;
						return false;
					}
					if(!($scope.oldName == $scope.vm.ifm_categoryName) && (opt_type==1)){
						$.layer({
        		            title: "温馨提示：",
        		            shade: [0],
        		            area: ['340', 'auto'],
        		            dialog: {
        		                msg: '所属该类别的类别名称都将更改，是否确认？',
        		                btns: 2,
        		                type: -1,
        		                btn: ['确定', '取消'],
        		                yes: function() {
        							ajaxFun();
        		                },
        		                no: function() {
        		                	avoidDup =true;
        		                }
        		            }
						});
					}else{
						ajaxFun();
					}
				}
				function ajaxFun(){
					$.ajax({
						type: "POST",
						url: basePath + urls[opt_type] + '?vtimes=' + new Date().getTime(),
						data: params,
						cache:false,
						error: function(request) {
							layer.msg("操作失败，请刷新重试！", 2, -1);
						},
						success: function(data) {
							var j = timeout_json(data, $window);
							if(j == false) {
								return false;
							}
							if(data.returnCode == 10000) {
								if(ifm_id){
									layer.msg(data.returnMessage, 1, 10);
								}else{
									layer.msg("正在运行,请稍后！", 2, 10);
								}
								$timeout(function(){
									if(opt_type==1){
										try {
											window.parent.$(".dtab").find('#jsgo a.cur').trigger('click');
										} catch(e) {}
										window.parent.layer.closeAll();
									}else{
										var index = parent.layer.getFrameIndex(window.name);
										try {
											window.parent.$('#Msearch').trigger('click');
										} catch(e) {}
										parent.layer.close(index);
									}
								},1000);
							} else {
								layer.msg(data.returnMessage, 2, -1);
								avoidDup =true;
								return false;
							}
						}
					});
				}
			}
		} 
	};
	//推送app勾选框
	$scope.domAjax2 = function(e) {
//		当推送方式为"否"，禁止勾选
		if($("#addIsSign").val()==1){
			var _ = $(e)
			if(_.attr('class').search('checked') > -1) {
				_.removeClass('checked');
			} else {
				_.addClass('checked');
			}
		}
	}
	$scope.cancel = function(e) {
		window.parent.layer.closeAll();
	}
	$scope.eShow = true;
	$scope.editFlag = false;
	//初始化数据
	$scope.initData = function(e) {
		//推送  $("#pushselect")
		var ispush = 0;
		if($scope.vm.ifm_pushed == 1) {
			ispush = 1;
			if(($scope.vm.ifm_type).indexOf('app') >-1||($scope.vm.ifm_type).indexOf('note') >-1){
				if(($scope.vm.ifm_type)=="app"){
					$("#push_app").addClass('checked');
				}else if(($scope.vm.ifm_type)=="note"){
					$("#push_msg").addClass('checked');
				}else if(($scope.vm.ifm_type)=="app|note"){
					$("#push_app").addClass('checked');
					$("#push_msg").addClass('checked');
				}
			}
		} 
		$("#addIsSign").val(ispush);
		
		if(ifm_id){
			$scope.eShow = false;
			if($scope.vm.groupId){
				$scope.showFlag = true;
				$scope.editFlag = true;
				$("#groupIds").val($scope.vm.groupId);
				$("#groupNameId").val($scope.vm.groupName);
//				$(".ui_s_bk a[data-id="+$scope.vm.groupId+"]").addClass("cur");
				if($scope.vm.ifm_category==null){
					$scope.vm.ifm_category="";
				}else{
					$("#categoryNameId").val($scope.vm.ifm_categoryName);
					$scope.oldName = $scope.vm.ifm_categoryName;
				}
			}else{
				$scope.showFlag = false;
				$scope.editFlag = false;
			}
		}else{
			$scope.showFlag = false;
			$scope.editFlag = true;
		}

		var selects = $("#pushselect").find('.ui_s_bk').find('a');
		$.each(selects, function(i, n) {
			if($(n).attr("type") == ispush) {
				$("#pushselect").find('.ui_s_t').text($(n).text());
			}
		});
		var isSensitive = 0;
		if($scope.vm.ifm_isSensitivity ==1){
			isSensitive = 1
		}
		$("#addIsSensitive").val(isSensitive);
		var sensitiveSelects = $("#sensitiveselect").find('.ui_s_bk').find('a');
		$.each(sensitiveSelects,function(i,n){
			if($(n).attr("type") == isSensitive){
				$("#sensitiveselect").find('.ui_s_t').text($(n).text());
			}
		});
	}
	
	$scope.editHidden = false;
	//查询数据初始化
	if(ifm_id != undefined) {
		$scope.editHidden = false;
		opt_type = 1;
		$http.get(basePath + 'iformation/queryByID2.do?ifm_id=' + ifm_id + '&groupId=' + groupIde).success(function(data) {
			var j = timeout_json(data, $window);
			if(j == false) {
				return false;
			}
			if(data.returnCode == 10000) {
				vm = $scope.vm = data.returnData;
				$scope.oldCategory = vm.ifm_category;
				$scope.oldCategoryName = vm.ifm_categoryName;
				if(vm.ifm_category!=null){
					$("#categoriesName").text(vm.ifm_category);
					$("#categoriesValue").val(vm.ifm_category);	
				}
			}
			$scope.initData();
		});
	} else {
		$scope.editHidden = true;
		opt_type = 0;
		$scope.initData();
	}
	
	//选择下拉框
	$('.ui_select').each(function() {
		var _ = $(this),
			_a = _.find('.ui_s_t'),
			_c = _.find('.ui_s_bk'),
			_ca = _c.find('a');
		_a.live('click', function() {
			_c.slideToggle(200, "easeInSine");
		});
		_ca.live('click', function() {
			$(this).addClass('cur').siblings().removeClass('cur');
			_a.text($(this).text());
//			区分下拉框
			$(this).parent().siblings("input").val($(this).attr("type"));
			
//			if(!ifm_id){
//			$("#categoryNameId").attr("readonly","readonly");
			if(!isNaN($("#groupIds").val()) && $("#groupIds").val()!="" && isNaN($(this).attr("type"))){
				param = {
					groupId:$("#groupIds").val(),
					category:$(this).attr("type")
				};
				$.ajax({
					type: "POST",
					url: basePath + "iformation/selectIfm_categoryNameByGroupId.do",
					data: param,
					cache:false,
					error: function(request) {
						layer.msg("操作失败，请刷新重试！", 2, -1);
					},
					success: function(data) {
						if(data.returnCode == 10000) {
							if(data.returnData){
								$scope.vm.ifm_categoryName = data.returnData.ifm_categoryName;
								if(!ifm_id){
									$("#categoryNameId").attr("readonly","readonly");
								}else{
									$("#categoryNameId").removeAttr("readonly");
								}
								$scope.$apply();
							}else{
								$scope.vm.ifm_categoryName = null;
									$("#categoryNameId").removeAttr("readonly");
								$scope.$apply();
							}
						}else{
							layer.msg(data.returnMessage, 1, 10);
							return false;
						}
					}
				});
			}
//			}else{
//				$("#categoryNameId").removeAttr("readonly");
//			}
			
			if($("#addIsSign").val()==0){
				$("#push_app,#push_msg").removeClass("checked");
			}
			_c.slideToggle(200, "easeInSine");
		});
		_c.live('mouseleave', function() {
			_c.stop(false, true).slideUp(200, "easeInSine");
		});
	});
	
});

app.directive('agSelect', function($http){
	return { 
		restrict:'AE',
/*		scope:{ 
			groupId:'=groupId'
		},*/
		template:'<div class="ui_select"><input type="text" id="groupInputText" class="ui_s_t" ng-bind="stxt" ng-model="stxt" /><div class="ui_s_bk"><a href="javascript:void(0)" ng-repeat="key in dataGroupSelects | filter: {groupName:stxt}" ng-bind="key.groupName" data-id="{{key.groupId}}"></a></div></div>',
		controller:function($scope,$element,$attrs){ 
			var a = $element.find('.ui_s_t'),
				b = $element.find('.ui_s_bk'),
				c = $attrs.ajaxs,
				d = $attrs.loadajaxs;
			$element.children('.ui_select').css('zIndex',102);
			$element.bind('click', function() {
				b.slideDown();
			});
			$element.bind('mouseleave', function() {
				if(a.text()!=""){
					b.hide();
				}
			});
		},
		link:function($scope,$element,$attrs){ 
			var a=$element.find('.ui_s_t'),
				b=$element.find('.ui_s_bk'),
				c=$attrs.ajaxs;
			if(c!=undefined){
				$http.get(c+'?vtimes='+new Date().getTime()).success(function(data){ 
					$scope.dataGroupSelects=data.returnData;
				});
			}			
			a.click(function() {
				$scope.stxt=undefined;
				$scope.$apply();
			});
			b.find('a').live("click",function(){ 
				b.hide();
				$(this).addClass('cur').siblings().removeClass('cur');
				a.val($(this).text());
				$scope.stxt=$(this).text();
				if($attrs.groupId!=undefined) {
					$scope.groupId=parseInt($(this).attr('data-id')); 
					$("#groupIds").val(parseInt($(this).attr('data-id')));
				}
				if($("#groupIds").val()!=""){
					$scope.showFlag = true;
				}
				$scope.$apply();
 				return false;
			});
			$element.bind('mouseleave',function(){ 
				$("#groupInputText").val(b.find('a.cur').text());
				b.find('.ui_s_t').blur();
				b.hide();
//				$scope.$apply();
				return false;
			});
		}
	}
});

$(function() {
	$('.ui_select').live('keyup', function(e) {
		var _ = $(this),
			b = _.find('.ui_s_bk'),
			di = 27;
			_.focus();
			e = e || window.event;
		var indx = b.find('a.cur').index() || 0;
		if(e.keyCode == 40) {
			var aindx = indx + 1,
				sct;
			if(rindx >= b.find('a').length) {
				rindx = b.find('a').length;
			}
			b.find('a').eq(aindx).addClass('cur').siblings('a').removeClass('cur');
			sct = aindx * di > 180 ? aindx * di - 80 : 0;
			b.scrollTop(sct);
		} else if(e.keyCode == 38) {
			var rindx = indx - 1,
				sct;
				sct = aindx * di > 100 ? aindx * di : 0;
			if(rindx <= 0) {
				rindx = 0;
			}
			b.find('a').eq(rindx).addClass('cur').siblings('a').removeClass('cur');
			sct = rindx * di > 180 ? rindx * di - 80 : 0;
			b.scrollTop(sct);
		} else if(e.keyCode == 13) {
			b.find('a.cur').trigger('click');
			_.blur();
			_.find('.ui_s_t').blur();
		}
		return false;
	});
});